package com.lhm.controller;


import com.lhm.entity.BookType;
import com.lhm.service.BookTypeService;
import com.lhm.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

//@CrossOrigin
@RestController
@RequestMapping("/api/adm/type")
//类型
public class BookTypeController {
    @Autowired
    BookTypeService bookTypeService;

//添加
    @RequestMapping("/add")
    public Map<String, Object> add(@RequestBody BookType bookType){
        if (bookType.getId()==0){
            bookTypeService.add(bookType.getType());
        }
        if (bookType.getId()>0){
            bookTypeService.update(bookType.getId(),bookType.getType());
        }
        List<BookType> lst = bookTypeService.findAll();
        return RespJson.pack(200,"添加成功",lst);
    }

    //查找全部
    @RequestMapping("/findAll")
    public Map<String,Object> findAll(){
        List<BookType> lst = bookTypeService.findAll();
        return RespJson.pack(200,"ok",lst);
    }

    @RequestMapping("/findById/{id}")
    public Map<String,Object> findById(@PathVariable Integer id){
        System.out.println(id);
        BookType byId = bookTypeService.findById(id);
        return RespJson.pack(200,"",byId);
    }
    /**
     * 自动转换日期类型的字段格式
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
}
